﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebChatDAL;
using System.Web.Security;

namespace WebChat.User
{
    public partial class Channel : System.Web.UI.Page
    {
        WebChatDAO dao = new WebChatDAO();

        protected void Page_Load(object sender, EventArgs e)
        {            
            if (!Page.IsPostBack)
            {
                string channelIdString = this.Request["channelId"];
                
                int channelId;

                if (!Int32.TryParse(channelIdString, out channelId))
                { 
                    this.LiteralError.Text = "Invalid channel Id (channelId must be int).";
                    return;
                }                

                WebChatDAL.Channel channel;
                if (!dao.TryGetChannelByChannelId(channelId, out channel))
                {
                    this.LiteralError.Text = "Invalid channel Id.";
                    return;
                }

                this.LiteralChannelName.Text = "Channel Name # " + Server.HtmlEncode(channel.ChannelName);
                this.Title = Server.HtmlEncode(channel.ChannelName);

                var messages = dao.GetLastNMessagesByChannelId(channelId, maxMessagesCount: 50);
                messages = messages.OrderBy(m => m.DateTimeSent);
                this.RepeaterMessages.DataSource= messages;
                this.RepeaterMessages.DataBind();

                List<int> messageIds = messages.Select(m => m.MessageId).ToList();
                ViewState["messageIds"] = messageIds;
            }
        }

        protected string SafeEval(string propertyName)
        {            
            string value = (string)Eval(propertyName);
            string safeValue = Server.HtmlEncode(value);

            return safeValue;
        }

        protected string EvalChatterUserName()
        {
            ChatterToChannelMessage message = (ChatterToChannelMessage)GetDataItem();

            if (message.Chatter != null)
            {
                return message.Chatter.aspnet_Users.UserName;
            }
            else
            {
                return "deleted user";
            }
        }
        
        protected string EvalSenderChatterId()
        {
            ChatterToChannelMessage message = (ChatterToChannelMessage)GetDataItem();

            return message.SenderChatterId.ToString();
        }
        
        protected void ButtonSendMessage_OnClick(object sender, EventArgs args)
        {
            string channelIdString = this.Request["channelId"];
                
            int channelId;

            if (!Int32.TryParse(channelIdString, out channelId))
            { 
                this.LiteralError.Text = "Invalid channel Id (channelId must be int).";
                return;
            }
          
            WebChatDAL.Channel channel;
            if (!dao.TryGetChannelByChannelId(channelId, out channel))
            {
                this.LiteralError.Text = "Invalid channel Id.";
                return;
            }

            string message = this.TextBoxMessage.Text.Trim();

            if (message == "")
            {
                return;
            }
            
            WebChatDAL.Chatter chatter;
            if(!dao.TryGetChatterByUserName(Page.User.Identity.Name, out chatter))
            {
                this.LiteralError.Text = String.Format("User with the username {0} was not found.", Page.User.Identity.Name);
                return;
            }

            dao.SendMessage_ChatterToChannel(chatter.ChatterId, channel.ChannelId, message);

            this.TextBoxMessage.Text = String.Empty;

            var messages = dao.GetLastNMessagesByChannelId(channelId, maxMessagesCount: 50);
            messages = messages.OrderBy(m => m.DateTimeSent);
            this.RepeaterMessages.DataSource = messages;
            this.RepeaterMessages.DataBind();
        }

        protected void TimerMessages_OnTick(object sender, EventArgs args)
        {
            string channelIdString = this.Request["channelId"];

            int channelId;

            if (!Int32.TryParse(channelIdString, out channelId))
            {
                this.LiteralError.Text = "Invalid channel Id (channelId must be int).";
                return;
            }
           
            WebChatDAL.Channel channel;
            if (!dao.TryGetChannelByChannelId(channelId, out channel))
            {
                this.LiteralError.Text = "Invalid channel Id.";
                return;
            }

            List<int> messageIdsOld = (List<int>)ViewState["messageIds"];
            
            var messages = dao.GetLastNMessagesByChannelId(channelId, maxMessagesCount: 50);
            messages = messages.OrderBy(m => m.DateTimeSent);

            List<int> messageIds = messages.Select(m => m.MessageId).ToList();

            if (messageIds.Except(messageIdsOld).Count() == 0 &&
                messageIdsOld.Except(messageIds).Count() == 0)
            {
                return; // no need to rebind grid view - no new messages
            }

            ViewState["messageIds"] = messageIds;

            this.RepeaterMessages.DataSource = messages;
            this.RepeaterMessages.DataBind();

            this.UpdatePanelMessages.Update();
        }

        protected void ButtonDeleteMessage_OnClick(object sender, EventArgs args)
        {
            Button button = (Button)sender;

            int messageId;
            if (Int32.TryParse(button.ToolTip, out messageId))
            {                
                if (dao.TryDeleteChannelMessageByMessageId(messageId, Page.User.Identity.Name))
                { 
                }
            }
        }
        
        protected int currentChatterId = -1;
        protected int CurrentChatterId
        {
            get 
            { 
                if(this.currentChatterId == -1)
                {
                    WebChatDAL.Chatter chatter;
                    if(dao.TryGetChatterByUserName(Page.User.Identity.Name, out chatter ))
                    {
                        this.currentChatterId = chatter.ChatterId;
                    }
                }

                return this.currentChatterId;
            }
        }

        protected bool EvalSenderChatterIdEqualsCurrentChatterId()
        {
            ChatterToChannelMessage message = (ChatterToChannelMessage)GetDataItem();
            return message.SenderChatterId == CurrentChatterId;
            
        }
    }
}